<template>
  <view class="example">
    <view class="page-editor-container">
      <sv-editor pasteMode="origin" @ready="ready" @input="input" @overmax="overMax" @epaste="epaste"></sv-editor>
    </view>
    <view class="page-editor-toolbar-container">
      <sv-editor-toolbar
        ref="toolbarRef"
        :style-tools="[
          'header',
          'divider',
          'bold',
          'italic',
          'underline',
          'strike',
          'align',
          'color',
          'backgroundColor',
          'removeformat'
        ]"
        @changeTool="changeTool"
        @toolMoreItem="onToolMoreItem"
        @moreItemConfirm="moreItemConfirm"
      >
        <template #at>
          <view class="panel-at">
            <view v-for="item in atList" :key="item.id" class="panel-at-item" @click="onAt(item)">
              {{ item.name }}
            </view>
          </view>
        </template>
        <template #topic>
          <view class="panel-topic">
            <view v-for="item in topicList" :key="item.id" class="panel-topic-item" @click="onTopic(item)">
              {{ item.name }}
            </view>
          </view>
        </template>
        <template #setting>
          <button size="mini" @click="onExport">导出</button>
        </template>
      </sv-editor-toolbar>
    </view>
  </view>
</template>

<script>
import SvEditorToolbar from '@/uni_modules/sv-editor/components/sv-editor/sv-editor-toolbar.vue'
import {
  addAt,
  addTopic,
  addAttachment,
  addImage,
  addLink,
  addVideo
} from '@/uni_modules/sv-editor/components/common/utils.js'

export default {
  components: {
    SvEditorToolbar
  },
  data() {
    return {
      atList: [
        { name: '马什么梅', id: 1 },
        { name: '什么冬梅', id: 2 },
        { name: '马冬什么', id: 3 }
      ],
      topicList: [
        { name: '今日资讯', id: 'news' },
        { name: '热搜', id: 'hot' },
        { name: '开心一下', id: 'happy' }
      ]
    }
  },
  mounted() {},
  methods: {
    ready(e) {
      console.log('==== ready ==== :', e)
      this.editorCtx = e
      this.editorCtx.initHtml(
        `<p style="text-align: center;">
      			<video controls width="80%" id="video-1"><source src="http://qiniu.sonve.asia/myvideos/cxk.mp4" /></video>
      	</p>
				<p style="text-align: center;">
						<video controls width="80%" id="video-2"><source src="http://qiniu.sonve.asia/myvideos/monkeybrother.mp4" /></video>
				</p>
        <p style="text-align: center;">
          🏀开发时长两年半🏀
        </p>`,
        async (videoUrl) => {
          let res

          // #ifdef APP || H5
          // res = await this.editorCtx.createVideoThumbnail(videoUrl)
          // #endif
          
          const fox = 'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg'
          res = await this.editorCtx.createCoverThumbnail(fox)
          
          return res
        }
      )
    },
    input(e) {
      console.log('input ==>', e)
    },
    epaste(e) {
      console.log('epaste ==>', e)
    },
    overMax(e) {
      console.log('overMax ==>', e)
    },
    changeTool(e) {
      console.log('changeTool ==>', e)
    },
    onToolMoreItem(e) {
      console.log('onToolMoreItem ==>', e)

      if (e.name == 'clear') {
        uni.showModal({
          title: '提示',
          content: '确定要清空内容吗？',
          success: ({ confirm }) => {
            if (confirm) {
              this.editorCtx.clear()
            }
          }
        })
      }
    },
    async moreItemConfirm(e) {
      console.log('moreItemConfirm ==>', e)

      // 添加图片
      if (e.name == 'image') {
        const imageRes = await addImage(
          async () => {
            // 开发者自行调用接口上传图片至服务器，此处只做模拟
            return new Promise((resolve) => {
              uni.showLoading({ title: '上传中' })
              setTimeout(() => {
                uni.hideLoading()
                let images = []
                if (e.link) images.push({ path: e.link }) // https://img.yzcdn.cn/vant/cat.jpeg
                if (e.file?.length) images = images.concat(e.file)
                resolve(images)
              }, 3000)
            })
          },
          { srcFiled: 'path' }
        )
        if (imageRes) {
          uni.showToast({ title: '添加图片成功', icon: 'success' })
        } else {
          uni.showToast({ title: '添加图片失败', icon: 'error' })
        }
      }

      // 添加视频
      if (e.name == 'video') {
        const videoRes = await addVideo(
          async (editorCtx) => {
            // 开发者自行调用接口上传图片至服务器，此处只做模拟
            return new Promise((resolve) => {
              uni.showLoading({ title: '上传中' })
              setTimeout(async () => {
                uni.hideLoading()
                let videos = []
                if (e.link) {
                  const linkThumbnail = await editorCtx.createVideoThumbnail(e.link)
                  videos.push({
                    imagePath: linkThumbnail,
                    tempFilePath: e.link // https://www.w3schools.com/html/movie.mp4
                  })
                }
                if (e.file.tempFilePath) {
                  const fileThumbnail = await editorCtx.createVideoThumbnail(e.file.tempFilePath)
                  // 视频封面
                  e.file.imagePath = fileThumbnail
                  videos.push(e.file)
                }
                resolve(videos)
              }, 3000)
            })
          },
          { imageFiled: 'imagePath', videoFiled: 'tempFilePath', width: '100%' }
        )
        if (videoRes) {
          uni.showToast({ title: '添加视频成功', icon: 'success' })
        } else {
          uni.showToast({ title: '添加视频失败', icon: 'error' })
        }
      }

      // 添加链接
      if (e.name == 'link') {
        addLink({ link: e.link, text: e.text }, () => {
          uni.showToast({ title: '添加链接成功' })
        })
      }

      // 添加附件
      if (e.name == 'attachment') {
        const attachmentRes = await addAttachment(async () => {
          // 开发者自行调用接口上传图片至服务器，此处只做模拟
          return new Promise((resolve) => {
            uni.showLoading({ title: '上传中' })
            setTimeout(() => {
              uni.hideLoading()
              let attachmentObj = e
              if (e.file.path) {
                attachmentObj.path = e.file.path
              } else if (e.link) {
                attachmentObj.path = e.link
              }
              resolve(attachmentObj)
            }, 3000)
          })
        })
        if (attachmentRes) {
          uni.showToast({ title: '添加附件成功', icon: 'success' })
        } else {
          uni.showToast({ title: '添加附件失败', icon: 'error' })
        }
      }

      // 关闭弹窗
      this.$refs.toolbarRef.closeMorePop()
    },
    onAt(e) {
      addAt({ username: e.name, userid: e.id }, () => {
        uni.showToast({ title: '艾特成功' })
      })
      // 关闭弹窗
      this.$refs.toolbarRef.closeMorePop()
    },
    onTopic(e) {
      addTopic({ topic: e.name, link: e.id }, () => {
        uni.showToast({ title: '添加话题成功' })
      })
      // 关闭弹窗
      this.$refs.toolbarRef.closeMorePop()
    },
    async onExport() {
      const contentRes = await this.editorCtx.getLastContent()
      const htmlHandler = this.editorCtx.exportHtml(contentRes.html)
      uni.navigateTo({
        url: '/pages/out/out',
        success: (res) => {
          res.eventChannel.emit('E_HTML_EXPORT', { data: htmlHandler })
        }
      })
    }
  }
}
</script>

<style lang="scss">
.example {
  box-sizing: border-box;
  height: calc(100vh - var(--window-top) - env(safe-area-inset-bottom));
  display: flex;
  flex-direction: column;

  .page-editor-container {
    flex: 1;
    overflow-y: auto;
    border: 10px solid #66ccff;
    box-sizing: border-box;
  }

  .page-editor-toolbar-container {
    position: sticky;
    bottom: 0;
    width: 100%;
    :deep(.sv-editor-toolbar) {
    }
  }
}

.panel-at,
.panel-topic {
  display: flex;
  flex-direction: column;

  .panel-at-item,
  .panel-topic-item {
    padding: 10px;
    margin: 10px 0;
    box-sizing: border-box;
    border-radius: 20rpx;
    box-shadow: 0 0 8px 6px rgba(0, 0, 0, 0.08);
  }
}
</style>
